<script setup lang="ts">
import { getCurrentInstance, ref, onBeforeMount, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const addrIds = ref([])
// --mescroll--
const noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const layer = ref()
const layerBox = ref()
const layerLoading = ref()

/* ---- */
const getCurrencyInfo = () => {
  // --获取信息--
  const forAddrData = {
    params: {
      'AddressSearch[dealer_id]': logUser.id,
      // ----
      page: 1,
      PageSize: 1000000000000
    }
  }
  proxy.$Axios.all([
    proxy.$Axios.get('address/index', forAddrData)
  ]).then(proxy.$Axios.spread((addrData) => {
    const addrItems = []
    addrData.items.forEach((item, index) => {
      addrItems.push(item.id)
    })
    addrIds.value = addrItems
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
}
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 10 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 10,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'address/index',
    forData: {
      params: {
        'AddressSearch[dealer_id]': logUser.id,
        // ----
        sort: 'SORT_DESC',
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    let forIcon = 'fal fa-circle xw-color-15'
    let forDefault = ''
    if (Number(item.is_default) === 1) {
      forIcon = 'fa fa-check-circle'
      forDefault = 'xw-color-11'
    }
    // ----
    const forCitys = String(item.province) === String(item.city) ? item.province + item.district : item.province + item.city + item.district
    const forAddress = Number(item.address.indexOf(forCitys)) === Number(-1) ? forCitys + proxy.$Myfun.setText(item.address) : proxy.$Myfun.setText(item.address)
    // ----
    newItems.push({
      id: item.id,
      name: proxy.$Myfun.setText(item.name),
      telphone: item.telphone,
      address: forAddress,
      is_default: item.is_default,
      iconStyle: forIcon,
      defaultStyle: forDefault
    })
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const setDefault = async (item) => {
  const arr = addrIds.value
  for (let i = 0; i < Number(arr.length); i++) {
    if (Number(arr[i]) === Number(item.id)) continue
    await proxy.$http.patch('address/update?id=' + arr[i], {
      is_default: 0,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
}
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      proxy.$Myfun.openPage(proxy, 'push', 'AddressAdm')
      break
    }
    case 2: {
      if (proxy.$route.query.addr_back) proxy.$Myfun.openPage(proxy, 'replace', proxy.$route.query.addr_back, { dealer_id: proxy.$route.query.dealer_id, goods_id: proxy.$route.query.goods_id, addr_id: item.id })
      break
    }
    case 3: {
      let layerCon = '是否设置为默认地址'
      if (Number(item.is_default) === 1) {
        layerCon = '不能取消默认地址'
        proxy.$Myfun.forToast(layer.value, 'open', layerCon)
        return false
      }
      // ----
      const options = {
        type: 0,
        title: proxy.$Global.layer.titleOne,
        content: layerCon,
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: '确定设置',
          class: 'xw-color-24',
          callback: async () => {
            layerBox.value.close()
            // ----
            proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
            await setDefault(item)
            // ----
            await proxy.$http.patch('address/update?id=' + item.id, {
              is_default: 1,
              // ----
              config_id: userInfo.config_id,
              openid: userInfo.openid
            }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
            // ----
            proxy.$Myfun.disLoading(layerLoading.value, 'close')
            mescroll.scrollTo(0)
            mescroll.resetUpScroll()
          }
        }]
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      break
    }
    case 4: {
      proxy.$Myfun.openPage(proxy, 'push', 'AddressAdm', { id: item.id })
      break
    }
    case 5: {
      if (Number(item.is_default) === 1) {
        proxy.$Myfun.forToast(layer.value, 'open', '默认地址不能被删除')
        return false
      }
      const options = {
        content: proxy.$Global.layer.conDel,
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: proxy.$Global.layer.btnDel,
          class: 'xw-color-24',
          callback: async () => {
            layerBox.value.close()
            // ----
            await proxy.$http.delete('address/delete?id=' + item.id, {
              config_id: userInfo.config_id,
              openid: userInfo.openid
            }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
            // ----
            mescroll.scrollTo(0)
            mescroll.resetUpScroll()
          }
        }]
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      break
    }
  }
}

/* ---- */
onBeforeMount(() => {
  getCurrencyInfo()
})
onMounted(() => {
  // --创建MeScroll对象--
  setTimeout(() => { startMeScroll() }, 500)
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => { if (mescroll) mescroll.destroy() })
</script>

<template>
  <div>
    <header class="xw-bg-gray">
      <div class="forTop xw-flex xw-flex-align">
        <div class="TOP-title xw-flex-W1">收货地址列表</div>
        <span class="TOP-submit xw-WBlue xw-radius-3" @click="getAuditFun(1)">新增地址</span>
      </div>
    </header>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <ul class="list-addr xw-flex xw-flex-column" ref="dataList">
          <li class="xw-bg-white xw-radius-3" v-for="(item, index) in items">
            <div class="xw-act" @click="getAuditFun(2, item)">
              <div class="LAR-desc">{{item.address}}</div>
              <div class="LAR-con xw-flex xw-flex-align xw-flex-justify">
                <div>{{item.name}}</div>
                <span>{{item.telphone}}</span>
              </div>
            </div>
            <div class="LAR-info xw-flex xw-flex-align xw-flex-justify">
              <div class="xw-act xw-flex-W1 xw-flex xw-flex-align" :class="item.defaultStyle" @click="getAuditFun(3, item)">
                <em :class="item.iconStyle"></em>
                <span>默认地址</span>
              </div>
              <div class="xw-btn xw-WBlue" @click="getAuditFun(4, item)">修改</div>
              <div class="LAR-fg xw-btn xw-WBlue" @click="getAuditFun(5, item)">删除</div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>

<style scoped>
/* ---- */
.list-addr li { position: relative; margin: 1rem 1rem 0; padding: 0 1rem; overflow: hidden; }
.list-addr li:nth-of-type(1) { margin-top: 0; }
.LAR-desc { padding: 1rem 0 0; line-height: 2.5rem; font-size: 1.5rem; }
.LAR-con { margin: 1rem 0 0; font-size: 1.5rem; }
.LAR-info { margin: 1rem 0 0; padding: 0 0 1rem; }
.LAR-info em { margin-right: 1rem; font-size: 2.4rem; }
.LAR-fg { margin-left: 1rem; }
</style>
